package com.incar.services;



import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.iflytek.aiui.AIUIListener;
import com.iflytek.aiui.AIUIMessage;
import com.iflytek.aiui.AIUISetting;
import com.incar.aiuidemo.R;
import com.incar.util.DeviceUtils;
import com.incar.util.FucUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;

public class AIUIListenerService extends Service {
    private static final String TAG = "AIUIservice";
    private static AIUIAgent mAIUIAgent = null;
    private boolean mIsWakeupEnable = false;
    private int mAIUIState = AIUIConstant.STATE_IDLE;
    private String mSyncSid = "";
    private boolean mIsAIUI_V2;
    private VoiceReceiver mReceiver;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter("com.incar.aiuidemo");
        mReceiver=new VoiceReceiver();
        registerReceiver(mReceiver, filter);
    }

 /*   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        createAgent();
        return super.onStartCommand(intent, flags, startId);
    }*/
    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 创建通知渠道（适用于Android 8.0及以上版本）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "default";
            String channelName = "Foreground Service";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
        }

        // 创建通知
        Notification notification = new NotificationCompat.Builder(this, "default")
                .setContentTitle("Service Running")
                .setContentText("AIUIListenerService is running.")
                .setSmallIcon(R.mipmap.logo)
                .build();

        // 将服务设置为前台服务
        startForeground(1, notification);

        // 执行你的服务逻辑
        createAgent();
        return START_STICKY;
    }

    private void createAgent() {
        if (checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
            return;
        }

        if (null == mAIUIAgent) {
            Log.i(TAG, "createAgent");

          /*  // 为每一个设备设置对应唯一的SN（最好使用设备硬件信息(mac地址，设备序列号等）生成），以便正确统计装机量，避免刷机或者应用卸载重装导致装机量重复计数
            String deviceId = DeviceUtils.getDeviceId(this);
            Log.i(TAG, "deviceId=" + deviceId);

            AIUISetting.setNetLogLevel(AIUISetting.LogLevel.debug);
            AIUISetting.setSystemInfo(AIUIConstant.KEY_SERIAL_NUM, deviceId);*/

            // 6.6.xxxx.xxxx版本SDK设置用户唯一标识uid（可选，AIUI后台服务需要，不设置则会使用上面的deviceId作为uid）
            // 5.6.xxxx.xxxx版本SDK不能也不需要设置uid
            // AIUISetting.setSystemInfo(AIUIConstant.KEY_UID, deviceId);
            AIUISetting.setSystemInfo(AIUIConstant.KEY_SERIAL_NUM, getSN() );
            AIUISetting.setSystemInfo(AIUIConstant.KEY_UID, getSN() );

            mAIUIAgent = AIUIAgent.createAgent(this, getAIUIParams(), mAIUIListener);
            startVoiceNlp();
        }

        if (null == mAIUIAgent) {
            final String strErrorTip = "创建AIUIAgent失败！";
            showTip(strErrorTip);

            //mNlpText.setText(strErrorTip);
        } else {
            showTip("AIUIAgent已创建");
        }
    }

    public static String getSN() {
        String serial = "";
        //通过android.os获取sn号
        try {
            serial = android.os.Build.SERIAL;
            if (!serial.equals("")&&!serial.equals("unknown"))return serial;
        }catch (Exception e){
            serial="";
        }
        //通过反射获取sn号
        try {
            Class<?> c =Class.forName("android.os.SystemProperties");
            Method get =c.getMethod("get", String.class);
            serial = (String)get.invoke(c, "ro.serialno");
            if (!serial.equals("")&&!serial.equals("unknown"))return serial;
        } catch (Exception e) {
            serial="";
        }
        return serial;
    }

    private void destroyAgent() {
        if (null != mAIUIAgent) {
            Log.i(TAG, "destroyAgent");

            mAIUIAgent.destroy();
            mAIUIAgent = null;

            showTip("AIUIAgent已销毁");
        } else {
            showTip("AIUIAgent为空");
        }
    }

    /**
     * 申请权限
     */
    private void requestPermissions(String[] perms) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //ActivityCompat.requestPermissions(this, perms, 0x0010);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getAIUIParams() {
        String params = FucUtil.readAssetFile(this, "cfg/aiui_phone.cfg", "utf-8");

        try {
            JSONObject paramsJson = new JSONObject(params);

            mIsWakeupEnable = !"off".equals(paramsJson.optJSONObject("speech").optString(
                    "wakeup_mode"));
            if (mIsWakeupEnable) {
                FucUtil.copyAssetFolder(this, "ivw", getApplicationContext().getExternalFilesDir(null) +"/sdcard/AIUI/ivw");
            }

            String aiuiVer = paramsJson.optJSONObject("global").optString("aiui_ver", "");
            mIsAIUI_V2 = (TextUtils.isEmpty(aiuiVer) || "2".equals(aiuiVer));

            params = paramsJson.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            ;
        }

        return params;
    }

    private final AIUIListener mAIUIListener = new AIUIListener() {
        @Override
        public void onEvent(AIUIEvent event) {
            Log.i(TAG, "onEvent, eventType=" + event.eventType);

            switch (event.eventType) {
                case AIUIConstant.EVENT_CONNECTED_TO_SERVER:
                    showTip("已连接服务器");
                    break;

                case AIUIConstant.EVENT_SERVER_DISCONNECTED:
                    showTip("与服务器断连");
                    break;


                case AIUIConstant.EVENT_WAKEUP:
                    showTip("进入识别状态");
                    //Log.d(TAG, "onEvent: EVENT_WAKEUP");
                  /*  Intent intent = new Intent(Intent.ACTION_VIEW,
                            //  Uri.parse("turing://com.turing.chat/assistant?type=0"));  //语音助手页
                            Uri.parse("turing://com.turing.chat/assistant?type=1"));  //唤醒页
                    //intent.setComponent(new ComponentName("com.turing.turingzhiwalauncher.assistant","com.turing.turingzhiwalauncher.assistant.ui.activity.AssistantChatActivity"));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("wakeUpSource","forSystemVoice");
                    getApplicationContext().startActivity(intent);*/
                    /*ComponentName cn = new ComponentName("com.turing.turingzhiwalauncher.assistant","com.turing.turingzhiwalauncher.assistant.ui.activity.AssistantChatActivity") ;
                    Intent intent3 = new Intent() ;
                    intent3.putExtra("isWake",true);
                    intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent3.setComponent(cn) ;
                    startActivity(intent3) ;*/
                   sendBroadcast(new Intent("com.incar.aiuidemo.star"));

                    break;

                case AIUIConstant.EVENT_RESULT: {


                }
                break;

                case AIUIConstant.EVENT_ERROR: {
                    showTip("开始AIUIConstant.EVENT_ERROR"+event.arg1);
                    switch(event.arg1){
                    case 11217:
                        showTip("开始听写");
                        Intent intent2 = new Intent(Intent.ACTION_VIEW,
                                //  Uri.parse("turing://com.turing.chat/assistant?type=0"));  //语音助手页
                                Uri.parse("turing://com.turing.chat/assistant?type=1"));  //唤醒页
                        //intent.setComponent(new ComponentName("com.turing.turingzhiwalauncher.assistant","com.turing.turingzhiwalauncher.assistant.ui.activity.AssistantChatActivity"));
                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent2.putExtra("wakeUpSource","forSystemVoice");

                        getApplicationContext().startActivity(intent2);
                        break;}
                }
                break;

                case AIUIConstant.EVENT_VAD: {
                    if (AIUIConstant.VAD_BOS == event.arg1) {
                        showTip("找到vad_bos");
                    } else if (AIUIConstant.VAD_EOS == event.arg1) {
                        showTip("找到vad_eos");
                    } else {
                        showTip("" + event.arg2);
                    }
                }
                break;

                case AIUIConstant.EVENT_START_RECORD: {
                    showTip("已开始录音");
                }
                break;

                case AIUIConstant.EVENT_STOP_RECORD: {
                    showTip("已停止录音");
                }
                break;

                case AIUIConstant.EVENT_STATE: {    // 状态事件
                    mAIUIState = event.arg1;

                    if (AIUIConstant.STATE_IDLE == mAIUIState) {
                        // 闲置状态，AIUI未开启
                        showTip("STATE_IDLE");
                    } else if (AIUIConstant.STATE_READY == mAIUIState) {
                        // AIUI已就绪，等待唤醒
                        showTip("STATE_READY");
                    } else if (AIUIConstant.STATE_WORKING == mAIUIState) {
                        // AIUI工作中，可进行交互
                        showTip("STATE_WORKING");
                    }
                }
                break;

                case AIUIConstant.EVENT_CMD_RETURN: {
                    if (AIUIConstant.CMD_SYNC == event.arg1) {    // 数据同步的返回
                        int dtype = event.data.getInt("sync_dtype", -1);
                        int retCode = event.arg2;

                        switch (dtype) {
                            case AIUIConstant.SYNC_DATA_UPLOAD:
                            case AIUIConstant.SYNC_DATA_SCHEMA: {
                                if (AIUIConstant.SUCCESS == retCode) {
                                    // 上传成功，记录上传会话的sid，以用于查询数据打包状态
                                    // 注：上传成功并不表示数据打包成功，打包成功与否应以同步状态查询结果为准，数据只有打包成功后才能正常使用
                                    mSyncSid = event.data.getString("sid");

                                    // 获取上传调用时设置的自定义tag
                                    String tag = event.data.getString("tag");

                                    // 获取上传调用耗时，单位：ms
                                    long timeSpent = event.data.getLong("time_spent", -1);
                                    /*if (-1 != timeSpent) {
                                        mTimeSpentText.setText(timeSpent + "ms");
                                    }*/

                                    showTip("上传成功，sid=" + mSyncSid + "，tag=" + tag + "，你可以试着说“打电话给刘德华”");
                                } else {
                                    mSyncSid = "";
                                    showTip("上传失败，错误码：" + retCode);
                                }
                            }
                            break;

                            case AIUIConstant.SYNC_DATA_DOWNLOAD: {
                                if (AIUIConstant.SUCCESS == retCode ) {
                                    String base64 = event.data.getString("text", "");
                                    String content = new String(Base64.decode(base64,
                                            Base64.DEFAULT));
                                    String text = "下载到的实体内容：\n" + content;

                                   // mNlpText.setText(text);
                                }
                            } break;
                        }
                    } else if (AIUIConstant.CMD_QUERY_SYNC_STATUS == event.arg1) {    // 数据同步状态查询的返回
                        // 获取同步类型
                        int syncType = event.data.getInt("sync_dtype", -1);
                        if (AIUIConstant.SYNC_DATA_QUERY == syncType) {
                            // 若是同步数据查询，则获取查询结果，结果中error字段为0则表示上传数据打包成功，否则为错误码
                            String result = event.data.getString("result");

                            showTip(result);
                        }
                    }
                }
                break;

                default:
                    break;
            }
        }
    };
    private void showTip(final String tip) {
        Log.d(TAG, "showTip: "+tip);
    }

    private void startVoiceNlp() {
        if (null == mAIUIAgent) {
            showTip("AIUIAgent为空，请先创建");
            return;
        }

        if (checkCallingOrSelfPermission(Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO});
            return;
        }

        Log.i(TAG, "startVoiceNlp");

        //mNlpText.setText("");

        // 先发送唤醒消息，改变AIUI内部状态，只有唤醒状态才能接收语音输入
        // 默认为oneshot模式，即一次唤醒后就进入休眠。可以修改aiui_phone.cfg中speech参数的interact_mode为continuous以支持持续交互
        if (!mIsWakeupEnable) {
            AIUIMessage wakeupMsg = new AIUIMessage(AIUIConstant.CMD_WAKEUP, 0, 0, "", null);
            mAIUIAgent.sendMessage(wakeupMsg);
        }

        // 打开AIUI内部录音机，开始录音。若要使用上传的个性化资源增强识别效果，则在参数中添加pers_param设置
        // 个性化资源使用方法可参见http://doc.xfyun.cn/aiui_mobile/的用户个性化章节
        // 在输入参数中设置tag，则对应结果中也将携带该tag，可用于关联输入输出
        String params = "sample_rate=16000,data_type=audio,pers_param={\"uid\":\"\"},tag=audio-tag";
        AIUIMessage startRecord = new AIUIMessage(AIUIConstant.CMD_START_RECORD, 0, 0, params,
                null);

        mAIUIAgent.sendMessage(startRecord);
    }

    private void stopVoiceNlp() {
        if (null == mAIUIAgent) {
            showTip("AIUIAgent 为空，请先创建");
            return;
        }

        Log.i(TAG, "stopVoiceNlp");

        // 停止录音
        String params = "sample_rate=16000,data_type=audio";
        AIUIMessage stopRecord = new AIUIMessage(AIUIConstant.CMD_STOP_RECORD, 0, 0, params, null);

        mAIUIAgent.sendMessage(stopRecord);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopVoiceNlp();
        unregisterReceiver(mReceiver);
        destroyAgent();
    }


    public  class VoiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: "+intent.getAction());
            if (intent.getAction().equals("com.incar.aiuidemo")){
                startVoiceNlp();
            }
        }
    }
    public static class BootCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: "+intent.getAction());
           // if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Intent serviceIntent = new Intent(context, AIUIListenerService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(serviceIntent);
                } else {
                    context.startService(serviceIntent);
                }
           // }
        }
    }
}
